package com.lijiayue.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT 工具类（推荐写法）
 */
@Component
public class JwtUtil {

    // 从 application.yml 读取密钥

    private final static String secret = "123456";

    // Token 过期时间（单位：毫秒）—— 1 小时
    private static final long EXPIRE_TIME = 60 * 60 * 1000;

    /**
     * 生成 token
     */
    public static String generateToken(Long userId, String userName) {
        Date now = new Date();
        Date expireAt = new Date(now.getTime() + EXPIRE_TIME);

        return JWT.create()
                .withSubject("login-token")
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withIssuedAt(now)
                .withExpiresAt(expireAt)
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 校验 token 是否有效
     */
    public boolean verify(String token) {
        try {
            getVerifier().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从 token 获取 userId
     */
    public Long getUserId(String token) {
        DecodedJWT decodedJWT = getVerifier().verify(token);
        return decodedJWT.getClaim("userId").asLong();
    }

    /**
     * 从 token 获取 userName
     */
    public String getUserName(String token) {
        DecodedJWT decodedJWT = getVerifier().verify(token);
        return decodedJWT.getClaim("userName").asString();
    }

    private JWTVerifier getVerifier() {
        return JWT.require(Algorithm.HMAC256(secret)).build();
    }
}
